package junior.util.math;

import java.io.Serializable;
import java.util.Collection;
import java.util.Map;
import java.util.Map.Entry;

/**
 * 单变量统计均值和标准差
 * 
 * @author ZhangXiaoye
 * @date 2016年11月25日 下午5:32:56
 */
public class OneVarStat implements Serializable{

	private static final long serialVersionUID = 1916615425598302778L;
	
	private int n = 0;
	private double sx = 0;
	private double sxx = 0;
	private double min = Double.MAX_VALUE;
	private double max = -Double.MAX_VALUE;
	
	public String toString(){
		if(n <= 0){
			return "OneVarStat(no sample)";
		}else{
			return String.format("OneVarStat(samples=%d, mean=%f, std=%f, min=%f, max=%f)", n, getMean(), getStdDev(), getMin(), getMax());
		}
	}

	public int add(final double x){
		sx += x;
		sxx += x * x;
		min = Math.min(min, x);
		max = Math.max(max, x);
		return n ++;
	}
	
	public int getN(){
		return n;
	}
	
	public double getMin(){
		return min;
	}
	
	public double getMax(){
		return max;
	}
	
	public double getMean(){
		return sx / n;
	}
	
	public double getStdDev(){
		return Math.sqrt(sxx / n - Math.pow(sx / n, 2));
	}
	
	public static boolean allAtLeastNSamples(Collection<OneVarStat> stats, int n){
		for(OneVarStat stat: stats){
			if(stat.getN() < n){
				return false;
			}
		}
		return true;
	}
	
	public static boolean allAtLeastNSamples(Map<? extends Object, OneVarStat> mapedStats, int n){
		for(Entry<? extends Object, OneVarStat> entry: mapedStats.entrySet()){
			if(entry.getValue().getN() < n){
				return false;
			}
		}
		return true;
	}
	
	
}
